import { Request, Response } from 'express'
import jwt from 'jsonwebtoken'
import { User } from '../models/User'

export const register = async (req: Request, res: Response) => {
  try {
    const { username, password, nickname } = req.body

    // 检查用户是否已存在
    const existingUser = await User.findOne({ username })
    if (existingUser) {
      return res.status(400).json({ message: '用户名已存在' })
    }

    // 创建新用户
    const user = new User({
      username,
      password,
      nickname,
    })

    await user.save()

    res.status(201).json({
      message: '注册成功',
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
      },
    })
  } catch (error) {
    res.status(500).json({ message: '服务器错误' })
  }
}

export const login = async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body

    // 查找用户
    const user = await User.findOne({ username })
    if (!user) {
      return res.status(401).json({ message: '用户名或密码错误' })
    }

    // 验证密码
    const isMatch = await user.comparePassword(password)
    if (!isMatch) {
      return res.status(401).json({ message: '用户名或密码错误' })
    }

    // 生成JWT
    const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET!, { expiresIn: '24h' })

    res.json({
      token,
      user: {
        id: user._id,
        username: user.username,
        nickname: user.nickname,
        role: user.role,
      },
    })
  } catch (error) {
    res.status(500).json({ message: '服务器错误' })
  }
}
